package com.xxx.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.mall.converter.SpuConverter;
import com.xxx.mall.dto.SkuDTO;
import com.xxx.mall.dto.SpuSkuAttrValueDTO;
import com.xxx.mall.mapper.SpuSkuAttrValueMapper;
import com.xxx.mall.model.SpuSkuAttrValue;
import com.xxx.mall.service.SpuSkuAttrValueService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品sku销售属性关联信息 服务实现类
 * </p>
 *
 * @author 邢晨旭
 * @since 2023-11-24
 */
@Service
public class SpuSkuAttrValueServiceImpl extends ServiceImpl<SpuSkuAttrValueMapper, SpuSkuAttrValue> implements SpuSkuAttrValueService {


    @Resource
    SpuConverter spuConverter;

    @Override
    public void updateBatchBySpuId(Long spuId, List<SkuDTO> updateSkus) {
        SpuSkuAttrValueService proxy = (SpuSkuAttrValueService) AopContext.currentProxy();
        List<Long> dbIds = baseMapper.queryIdsBySpuId(spuId);
        List<SpuSkuAttrValue> addList = new ArrayList<>();
        List<SpuSkuAttrValue> updateList = new ArrayList<>();
        updateSkus.forEach(sku -> {
            List<SpuSkuAttrValueDTO> skuAttrValues = sku.getSpuSkuAttrValues();
            skuAttrValues.forEach(dto -> {
                //新增
                if (dto.getSpuSkuAttrId() == null) {
                    addList.add(spuConverter.toSpuSkuAttrValue(dto));
                } else {
                    //修改
                    if (dbIds.contains(dto.getSpuSkuAttrId())) {
                        updateList.add(spuConverter.toSpuSkuAttrValue(dto));
                        dbIds.remove(dto.getSpuSkuAttrId());
                    }
                }
            });
        });
        if (CollUtil.isNotEmpty(addList)) {
            proxy.saveBatch(addList);
        }
        if (CollUtil.isNotEmpty(updateList)) {
            proxy.updateBatchById(updateList);
        }
        if (CollUtil.isNotEmpty(dbIds)) {
            baseMapper.removeBatchIds(dbIds);
        }
    }
}
